<template>
  <div class="config-edit">
    <div class="page-header">
      <div class="header-left">
        <h3>{{ isEdit ? '编辑' : '新建' }}全局配置</h3>
        <p>管理系统的全局默认配置</p>
      </div>
      <div class="header-right">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" :loading="saving" @click="handleSave">
          {{ saving ? '保存中...' : '保存' }}
        </el-button>
      </div>
    </div>

    <div class="edit-content">
      <el-card>
        <el-form
          ref="configFormRef"
          :model="configForm"
          :rules="configRules"
          label-width="120px">

          <el-form-item label="配置名称" prop="name">
            <el-input v-model="configForm.name" placeholder="请输入配置名称" />
          </el-form-item>

          <el-form-item label="文件路径" prop="filePath">
            <el-input v-model="configForm.filePath" placeholder="如：./config.json" />
          </el-form-item>

          <el-form-item label="变更说明" prop="changeSummary">
            <el-input
              v-model="configForm.changeSummary"
              type="textarea"
              :rows="2"
              placeholder="请简要描述此次变更内容" />
          </el-form-item>

          <!-- 一键获取配置 -->
          <el-form-item label="智能配置">
            <div class="smart-config-section">
              <div class="input-with-button">
                <el-input
                  v-model="contractAddress"
                  placeholder="输入合约地址自动生成配置（如：0x477c2c0459004e3354ba427fa285d7c053203c0e）"
                  clearable
                  @input="handleContractAddressChange" />
                <el-button
                  type="primary"
                  :loading="fetchingTokenInfo"
                  :disabled="!contractAddress || !/^0x[a-fA-F0-9]{40}$/.test(contractAddress)"
                  @click="fetchTokenInfo">
                  生成配置
                </el-button>
              </div>
              <div class="help-text">
                输入合约地址，系统将自动调用Binance API获取代币信息并生成配置
              </div>
            </div>
          </el-form-item>

          <el-form-item label="配置内容" prop="configContent">
            <JsonEditor v-model="configForm.configContent" :height="300" />
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { reactive, ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { http } from '@/utils/request'
import { ElMessage } from 'element-plus'
import TokenService from '@/utils/tokenService'
import JsonEditor from '@/components/JsonEditor.vue'

const route = useRoute()
const router = useRouter()

// 路由参数
const configId = ref(route.params.id ? parseInt(route.params.id) : null)
const isEdit = computed(() => !!configId.value)

// 表单引用
const configFormRef = ref()

// 状态
const saving = ref(false)
const fetchingTokenInfo = ref(false)
const contractAddress = ref('')

// 配置表单
const configForm = reactive({
  name: '',
  filePath: '',
  changeSummary: '',
  configContent: '{\n  "name": "示例项目",\n  "baseAsset": "TOKEN",\n  "quoteAsset": "USDT",\n  "chainId": 56,\n  "contractAddress": "0x...",\n  "buyAmount": 100,\n  "targetBuyQuote": 10000,\n  "proxy": false,\n  "notifyUrl": ""\n}'
})

// 表单验证规则
const configRules = {
  name: [
    { required: true, message: '请输入配置名称', trigger: 'blur' },
    { max: 100, message: '配置名称不能超过100个字符', trigger: 'blur' }
  ],
  changeSummary: [
    { max: 500, message: '变更说明不能超过500个字符', trigger: 'blur' }
  ],
  configContent: [
    { required: true, message: '请输入配置内容', trigger: 'blur' },
    { validator: validateJson, trigger: 'blur' }
  ]
}

// JSON验证器
function validateJson(rule, value, callback) {
  if (!value) {
    callback(new Error('请输入配置内容'))
    return
  }

  try {
    JSON.parse(value)
    callback()
  } catch (error) {
    callback(new Error('配置内容必须是有效的JSON格式'))
  }
}

// 初始化
onMounted(async () => {
  if (isEdit.value) {
    await loadConfigDetail()
  }
})

// 加载配置详情
const loadConfigDetail = async () => {
  try {
    const response = await http.get(`/configs/${configId.value}`)
    const detail = response.data

    Object.assign(configForm, {
      name: detail.name,
      filePath: detail.filePath || '',
      changeSummary: '',
      configContent: detail.configContent
    })
  } catch (error) {
    ElMessage.error('加载配置详情失败')
    router.back()
  }
}

// 保存配置
const handleSave = async () => {
  if (!configFormRef.value) return

  try {
    await configFormRef.value.validate()
    saving.value = true

    if (isEdit.value) {
      await http.put(`/configs/${configId.value}`, configForm)
      ElMessage.success('配置更新成功')
    } else {
      await http.post('/configs', configForm)
      ElMessage.success('配置创建成功')
    }

    router.back()
  } catch (error) {
    if (error.message) {
      ElMessage.error(error.message)
    }
  } finally {
    saving.value = false
  }
}

// 获取代币信息并生成配置
const fetchTokenInfo = async () => {
  if (!contractAddress.value) {
    ElMessage.warning('请先输入合约地址')
    return
  }

  fetchingTokenInfo.value = true
  try {
    const tokenInfo = await TokenService.getTokenInfo(contractAddress.value, 56)

    // 使用symbol作为配置名称
    configForm.name = tokenInfo.symbol

    // 生成完整的配置JSON
    const config = {
      name: tokenInfo.name,
      baseAsset: TokenService.generateBaseAsset(tokenInfo),
      quoteAsset: "USDT",
      chainId: 56,
      contractAddress: tokenInfo.contractAddress,
      buyAmount: 100,
      targetBuyQuote: 10000,
      proxy: false,
      notifyUrl: "",
      // 额外的代币信息
      symbol: tokenInfo.symbol,
      decimals: tokenInfo.decimals,
      description: tokenInfo.description
    }

    // 美化JSON格式
    configForm.configContent = JSON.stringify(config, null, 2)

    ElMessage.success(`已生成 ${tokenInfo.symbol} 的配置`)

    // 清空合约地址输入框
    contractAddress.value = ''

  } catch (error) {
    ElMessage.error(error.message || '获取代币信息失败')
  } finally {
    fetchingTokenInfo.value = false
  }
}

// 处理合约地址输入变化
const handleContractAddressChange = () => {
  // 可以在这里添加额外的逻辑
}

// 取消编辑
const handleCancel = () => {
  router.back()
}
</script>

<style lang="scss" scoped>
.config-edit {
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding: 20px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

    .header-left {
      h3 {
        margin: 0 0 5px;
        color: #303133;
        font-size: 18px;
        font-weight: 600;
      }

      p {
        margin: 0;
        color: #606266;
        font-size: 14px;
      }
    }
  }

  .edit-content {
    :deep(.el-card__body) {
      padding: 30px;
    }

    .smart-config-section {
      .input-with-button {
        display: flex;
        gap: 8px;
        align-items: stretch;
        margin-bottom: 8px;

        .el-input {
          flex: 1;
        }

        .el-button {
          flex-shrink: 0;
          white-space: nowrap;
        }
      }

      .help-text {
        font-size: 12px;
        color: #909399;
        line-height: 1.4;
      }
    }
  }
}
</style>
